package com.sneakxy.mybatis.commons.dialect;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.mapping.ParameterMapping;
import org.apache.ibatis.session.Configuration;
import org.springframework.data.domain.Pageable;

public class MySqlDialect extends Dialect {
	
	public static final String DIALECT_NAME = "MYSQL";
	
	public static final String REGEX_KEY = "REGEXP";

	/**
	 * @param configuration
	 */
	public MySqlDialect(Configuration configuration) {
		super(configuration);
	}

	@Override
	protected ProcessHandler onProcess(String sql, Map<String, Object> parameterValues, Pageable page) {
		final StringBuilder _sql = new StringBuilder().append(sql);
		_sql.append(" limit ?, ?");
		List<ParameterMapping> _params = new ArrayList<ParameterMapping>();
		_params.add(new ParameterMapping.Builder(this.getConfiguration(), "offset", Long.class).build());
		_params.add(new ParameterMapping.Builder(this.getConfiguration(), "pageSize", Integer.class).build());
		return new ProcessHandler(_sql.toString(), _params);
	}

	@Override
	protected boolean isProcessed(String sql, Map<String, Object> parameterValues, Pageable page) {
		return StringUtils.indexOfIgnoreCase(sql, "limit") > -1;
	}

	/* (non-Javadoc)
	 * @see com.sneakxy.mybatis.commons.dialect.Dialect#setProcessedParameters(java.util.Map, org.springframework.data.domain.Pageable)
	 */
	@Override
	protected void setParameterValues(Map<String, Object> parameterValues, Pageable page) {
		parameterValues.put("offset", page.getOffset());
		parameterValues.put("pageSize", page.getPageSize());
	}

	/* (non-Javadoc)
	 * @see com.sneakxy.mybatis.commons.dialect.Dialect#needSequenceIdColumnSql()
	 */
	@Override
	public boolean needSequenceIdColumnSql() {
		return false;
	}

	@Override
	public String buildRegexSql(String column, String value) {
		return StringUtils.join(column, " ", REGEX_KEY, " ", value);
	}

	@Override
	protected String formatSimpleColumnName(String columnName) {
		return StringUtils.join("`", columnName, "`");
	}

	/* (non-Javadoc)
	 * @see com.sneakxy.mybatis.commons.dialect.Dialect#getSequenceIdColumnValue(java.lang.String)
	 */
	@Override
	public String getSequenceIdColumnValue(String generator) {
		return null;
	}

	/* (non-Javadoc)
	 * @see com.sneakxy.mybatis.commons.dialect.Dialect#getSequenceIdSql(java.lang.String, java.lang.String, java.lang.String)
	 */
	@Override
	public String getSequenceIdSql(String generator, String idColumn) {
		return "SELECT LAST_INSERT_ID()";
	}

	/* (non-Javadoc)
	 * @see com.sneakxy.mybatis.commons.dialect.Dialect#upperFunction(java.lang.String)
	 */
	@Override
	public String upperFunction(String column) {
		return new StringBuilder().append("upper(").append(column).append(")").toString();
	}

}
